﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace LiveProjectManager.DDD.Services
{
    public class PostService : Base.Service<Domains.Post>
    {
        public PostService() : base()
        {
        }


        override public ICollection<Domains.Post> getAll(int paginateBy = 0, int page = 1)
        {
            if (paginateBy > 0)
            {
                if (page <= 0)
                    page = 1;
                return (from p in _repository orderby p.Id select p).Skip(paginateBy * (page - 1)).Take(paginateBy).ToList();
            }
            return (from p in _repository orderby p.Id select p).ToList();
        }


        override public Domains.Post getById(long myId)
		{
            ICollection<Domains.Post> myResults = (from p in _repository 
                                                          where p.Id == myId
                                                   select p).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public ICollection<Domains.Post> getBySender(Domains.User mySender)
		{
			return (from p in _repository where p.User.Id == mySender.Id select p).ToList();
        }


        public bool create(string myContent, Domains.User mySender, bool autoSave = true)
		{
            try
            {
                if (myContent.Length == 0)
                    return false;
                Domains.Post myNewPost = new Domains.Post
                {
                    Content = myContent,
                    User = mySender
                };
                myNewPost.CreatedOn = DateTime.Now;
                _repository.Add(myNewPost);
                if (autoSave)
                    _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        override public bool remove(long myId, bool autoSave = true)
        {
            Domains.Post myPost = getById(myId);
            if (myPost == null)
                return false;
            _repository.Remove(myPost);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }
    }
}